<script setup lang="ts">
import { onMounted, ref, nextTick, reactive, h, computed } from "vue";
import { useRouter } from "vue-router";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { UploadProps, UploadUserFile } from "element-plus";
import { UploadFilled, Document } from "@element-plus/icons-vue";
import {
  queryTaskList,
  queryTaskData,
  deleteTask,
  uploadAssetFile,
} from "../servers";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { StatusTag } from "@/components/DynamicTable/components";
import SyncHistoryDialog from "@/views/taskmg/alltask/components/SyncHistoryDialog.vue";

const props = defineProps<{
  // 任务列表页面不需要props
}>();

const router = useRouter();
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const taskList = ref([]);
const loading = ref(false);

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();

const columns = ref<TableColumn[]>([
  {
    label: "任务名称",
    prop: "task_name",
    show: true,
    render: (row, column, cellValue, index) => {
      return h(
        "span",
        {
          style: {
            color: "#409eff",
            cursor: "pointer",
            textDecoration: "underline",
          },
          onClick: () => handleViewTask(row),
        },
        cellValue
      );
    },
  },
  {
    label: "任务ID",
    prop: "id",
    show: true,
  },
  {
    label: "创建时间",
    prop: "created_at",
    show: true,
    render: (row, column, cellValue, index) => {
      if (!cellValue) return "-";
      const date = new Date(cellValue);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      });
    },
  },
  {
    label: "操作",
    prop: "action",
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

// 搜索表单数据
const searchFormData = reactive({
  task_name: "",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    placeholder: "请输入任务名称",
    params: {
      clearable: true,
      style: { width: "200px" },
    },
  },
];

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteTask({ task_id: row.id });
      ElMessage.success("删除成功");
      getPageData();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

const getPageData = async () => {
  loading.value = true;

  try {
    const response = await queryTaskList({
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      task_name: searchFormData.task_name || undefined,
    });

    if (response.code === 2000) {
      taskList.value = response.data.tasks || [];
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(response.message || "获取数据失败");
      taskList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
    taskList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getPageData();
});

const handleSearch = (value: any) => {
  // 更新搜索表单数据
  searchFormData.task_name = value.task_name || "";
  pagination.currentPage = 1;
  getPageData();
};

const handleSearchReset = () => {
  // 重置表单数据
  searchFormRef.value?.resetFields();
  searchFormData.task_name = "";
  pagination.currentPage = 1;
  getPageData();
};

const handlePaginationChange = (page: number) => {
  pagination.currentPage = page;
  getPageData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getPageData();
};

// 点击任务查看详情
const handleViewTask = (row: any) => {
  router.push({
    path: `/asset-report/asset-management-platform/task/${row.id}`,
    query: {
      taskName: row.task_name,
    },
  });
};

// 上传资产对话框相关状态
const uploadDialogVisible = ref(false);
const uploadForm = ref({
  task_name: "",
});
const fileList = ref<UploadUserFile[]>([]);
const selectedFile = ref<File | null>(null);
const uploading = ref(false);
const uploadFormRef = ref();

// 同步历史弹窗相关
const showSyncHistoryDialog = ref(false);
const syncHistoryTaskId = ref(0);
const syncHistoryTaskName = ref("");

// 表单校验规则
const uploadRules = {
  task_name: [
    { required: true, message: "请输入任务名称", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "任务名称长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
};

// 计算按钮是否应该禁用
const isUploadDisabled = computed(() => {
  // 只在上传过程中禁用按钮
  return uploading.value;
});

// 打开上传资产对话框
const handleOpenUploadDialog = () => {
  uploadForm.value = {
    task_name: "",
  };
  fileList.value = [];
  selectedFile.value = null;
  uploading.value = false;
  uploadDialogVisible.value = true;
};

// 取消上传
const handleCancelUpload = () => {
  uploadDialogVisible.value = false;
  uploadForm.value = {
    task_name: "",
  };
  fileList.value = [];
  selectedFile.value = null;
  uploading.value = false;
};

// 预上传处理 - 只验证文件，不实际上传
const beforeUpload: UploadProps["beforeUpload"] = async (rawFile) => {
  // 验证文件类型
  const allowedTypes = [
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel",
  ];
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error("只支持Excel文件格式");
    return false;
  }

  // 验证文件大小 (10MB)
  const maxSize = 10 * 1024 * 1024;
  if (rawFile.size > maxSize) {
    ElMessage.error("文件大小不能超过10MB");
    return false;
  }

  // 保存选中的文件
  selectedFile.value = rawFile;
  ElMessage.success("文件选择成功，请填写任务名称后点击确认上传");

  // 返回true让文件添加到fileList中，但阻止实际上传
  return true;
};

// 阻止自动上传
const handleUploadError = () => {
  // 什么都不做，只是阻止自动上传
};

// 打开同步历史弹窗
const handleOpenSyncHistory = (row: any) => {
  syncHistoryTaskId.value = row.id;
  syncHistoryTaskName.value = row.task_name || "";
  showSyncHistoryDialog.value = true;
};

// 查看同步详情
const handleViewSyncDetail = (runId: string) => {
  // TODO: 打开网管对比结果弹窗
  console.log("查看同步详情，runId:", runId);
  ElMessage.info("网管对比结果弹窗功能待实现");
};

// 确认上传
const handleConfirmUpload = async () => {
  // 使用表单校验
  if (!uploadFormRef.value) return;

  try {
    await uploadFormRef.value.validate();
  } catch (error) {
    return; // 表单校验失败，不继续执行
  }

  // 验证是否选择了文件 - 检查fileList或selectedFile
  const hasFile =
    (fileList.value && fileList.value.length > 0) || selectedFile.value;
  if (!hasFile) {
    ElMessage.error("请选择要上传的文件");
    return;
  }

  uploading.value = true;

  try {
    const formData = new FormData();
    formData.append("task_name", uploadForm.value.task_name);

    // 优先使用selectedFile，如果没有则使用fileList中的文件
    let fileToUpload = selectedFile.value;
    if (!fileToUpload && fileList.value && fileList.value.length > 0) {
      fileToUpload = fileList.value[0].raw;
    }

    formData.append("file", fileToUpload);

    const response = await uploadAssetFile(formData);

    if (response.code === 2000) {
      ElMessage.success("资产上传成功");
      uploadDialogVisible.value = false;
      uploadForm.value = {
        task_name: "",
      };
      fileList.value = [];
      selectedFile.value = null;
      // 刷新数据
      getPageData();
    } else {
      ElMessage.error(response.message || "上传失败");
    }
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("上传失败");
  } finally {
    uploading.value = false;
  }
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-card shadow="never">
    <div class="search-form-container">
      <DynamicForm
        ref="searchFormRef"
        v-model="searchFormData"
        :form-config="searchFormConfig"
        :gutter="16"
        label-width="80px"
        type="search"
        @search="handleSearch"
        @reset="handleSearchReset"
      />
    </div>
  </el-card>
  <div style="height: 10px"></div>
  <el-card>
    <DynamicTable
      :pagination="pagination"
      :columns="columns"
      :data="taskList"
      :loading="loading"
      @current-page-change="handlePaginationChange"
      @size-change="handleSizeChange"
    >
      <template #toolbar-left>
        <el-button type="primary" @click="handleOpenUploadDialog">
          上传资产
        </el-button>
      </template>
      <template #action="{ row }">
        <el-button type="primary" size="small" @click="handleViewTask(row)">
          查看
        </el-button>
        <el-button
          type="success"
          size="small"
          @click="handleOpenSyncHistory(row)"
        >
          网管同步历史
        </el-button>
        
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
    </DynamicTable>
  </el-card>

  <!-- 上传资产对话框 -->
  <el-dialog
    v-model="uploadDialogVisible"
    title="上传资产"
    width="500px"
    destroy-on-close
    @close="handleCancelUpload"
  >
    <el-form
      ref="uploadFormRef"
      :model="uploadForm"
      :rules="uploadRules"
      label-width="100px"
    >
      <el-form-item label="任务名称" prop="task_name" required>
        <el-input
          v-model="uploadForm.task_name"
          placeholder="请输入任务名称"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="文件" required>
        <el-upload
          class="upload-demo"
          drag
          v-model:file-list="fileList"
          :limit="1"
          :before-upload="beforeUpload"
          :on-error="handleUploadError"
          accept=".xls,.xlsx"
          :auto-upload="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖动文件上传 或者<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              请上传资产文件，仅支持.xls和.xlsx格式
            </div>
          </template>
        </el-upload>
        <div v-if="selectedFile" class="selected-file-info">
          <el-icon><Document /></el-icon>
          <span>{{ selectedFile.name }}</span>
          <span class="file-size"
            >({{ (selectedFile.size / 1024 / 1024).toFixed(2) }}MB)</span
          >
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelUpload">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirmUpload"
          :loading="uploading"
          :disabled="isUploadDisabled"
        >
          {{ uploading ? "上传中..." : "确认上传" }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 同步历史弹窗 -->
  <SyncHistoryDialog
    v-model="showSyncHistoryDialog"
    :task-id="syncHistoryTaskId"
    :task-name="syncHistoryTaskName"
    @close="showSyncHistoryDialog = false"
    @view-detail="handleViewSyncDetail"
  />
</template>

<style scoped lang="scss">
// 标签样式
:deep(.el-tag) {
  margin-right: 4px;
  margin-bottom: 2px;
}

// 标签输入框样式
:deep(.el-input.is-small .el-input__inner) {
  height: 24px;
}

// 详情对话框样式
.detail-container {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.info-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  word-break: break-word;
  flex: 1;
}

.json-container {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  border: 1px solid #e4e7ed;

  :deep(.jv-container) {
    background: transparent;

    .jv-code {
      background: transparent;
      padding: 0;
    }
  }
}

.code-block {
  background: #282c34;
  color: #abb2bf;
  padding: 16px;
  border-radius: 6px;
  font-family: "Courier New", Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

// 状态修改弹窗样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.selected-file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  color: #0369a1;

  .file-size {
    color: #64748b;
    font-size: 12px;
  }
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

// 响应式设计
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    margin-bottom: 4px;
  }
}
</style>
